package com.shinhye.elephantsafe.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

public class LocationService extends Service {
	private MyLocationListener listener;
	private LocationManager locMan;
	private SharedPreferences sp;

	@Override
	public void onCreate() {
		System.out.println("Location Service开启了");
		locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
		sp = getSharedPreferences("Setting", MODE_PRIVATE);
		
		//条件
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
		criteria.setBearingRequired(false);
		criteria.setAltitudeRequired(false);
		criteria.setCostAllowed(true);
		String bestProvider = locMan.getBestProvider(criteria, true);

		listener = new MyLocationListener();
		locMan.requestLocationUpdates(bestProvider == null ? "gps" : bestProvider, 0, 0, listener);

	}

	class MyLocationListener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			System.out.println("Location--位置变化了");
			Editor editor = sp.edit();
			editor.putString("location",
					"\nLongitude:" + location.getLongitude() + ";\nLatitude:"
							+ location.getLatitude() + ";\nAccuracy:"
							+ location.getAccuracy() + ".\n");
			editor.commit();
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			System.out.println("Location provider状态变化了");
		}

		@Override
		public void onProviderEnabled(String provider) {
			System.out.println("某一个Location提供者可用了");
		}

		@Override
		public void onProviderDisabled(String provider) {
			System.out.println("某一个Location提供者不可用了");
		}
	}

	@Override
	public void onDestroy() {
		System.out.println("Location Service销毁了!");
		super.onDestroy();
		locMan.removeUpdates(listener);
		listener = null;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
